package controller

import (
	"encoding/json"
	"github.com/gofiber/fiber/v2"
	"log"
	"os"
)

func init() {
	RegisterRoute(func(app *fiber.App) {
		homeView := app.Group("/home")
		homeView.Get("", home)
	})
}

// readRouterJSON 读取 router.json 文件并解析
func readRouterJSON() (string, error) {
	filePath := "router.json"
	log.Printf("Trying to open file: %s", filePath)
	file, err := os.Open(filePath)
	if err != nil {
		log.Printf("Failed to open file: %v", err)
		return "", err
	}
	defer file.Close()

	var data interface{}
	err = json.NewDecoder(file).Decode(&data)
	if err != nil {
		log.Printf("Failed to decode JSON: %v", err)
		return "", err
	}

	jsonData, err := json.Marshal(data)
	if err != nil {
		log.Printf("Failed to marshal JSON: %v", err)
		return "", err
	}

	return string(jsonData), nil
}
func home(c *fiber.Ctx) error {
	// 读取 router.json 文件
	routerData, err := readRouterJSON()
	if err != nil {
		return c.Status(fiber.StatusInternalServerError).SendString(err.Error())
	}

	// 将数据添加到传递给模板的 fiber.Map 中
	data := fiber.Map{
		"Title":      "welcome to fqyb",
		"RouterData": routerData,
	}

	return c.Render("home", data)
}
